package com.ksyun.cloudhostalarmprocessing.scheduled;

import com.ksyun.cloudhostalarmprocessing.entity.Alerts;
import com.ksyun.cloudhostalarmprocessing.entity.Exceed;
import com.ksyun.cloudhostalarmprocessing.entity.Rules;
import com.ksyun.cloudhostalarmprocessing.entity.vo.MetricsVO;
import com.ksyun.cloudhostalarmprocessing.entity.vo.RateVO;
import com.ksyun.cloudhostalarmprocessing.service.IAlertsService;
import com.ksyun.cloudhostalarmprocessing.service.IMetricsService;
import com.ksyun.cloudhostalarmprocessing.service.IRulesService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;
import org.springframework.web.bind.annotation.PathVariable;

import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.List;
import java.util.Objects;
@Slf4j
@Component
public class ScheduledTasks {

    @Autowired
    IMetricsService metricsService;
    @Autowired
    IRulesService rulesService;
    @Autowired
    IAlertsService alertsService;
    //使用日期时间格式化器设置日期和时间
    DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");

//    @Value("${schedule.date}")
    String date = "2024-05-17 14:30:00"; //"2024-04-17 13:55:00"
    LocalDateTime dateTime = LocalDateTime.parse(date, formatter);
    //主机内存使用率是否超过80%
    private Boolean TheNumberIsExceed(Exceed exceed,Float warmingValue) {

        //(1-((node memory Buffers bytes + node memory Cached bytes +
        //node memory MemFree bytes)/node memory MemTotal bytes))*100>
        //80
        if ((1- ((exceed.getNodeMemoryBuffersBytes()+exceed.getNodeMemoryCachedBytes()+ exceed.getNodeMemoryMemFreeBytes())/ exceed.getNodeMemoryMemTotalBytes()))*100>warmingValue){
            return true;
        }
        return false;
    }

    public Boolean isTooHigh(RateVO rateVO,Float warmingValue){
        if (rateVO.getResult()>warmingValue){
            return true;
        }
        return false;
    }
    @Scheduled(fixedRate = 30000)  // 每隔5秒执行一次
    public void reportCurrentTime() {
        List<Rules> rules = rulesService.selectBatch(new Rules());
        for (Rules rule : rules) {
            if (rule.getMetricName().equals("many1")){
                //查询大于80%
                List<MetricsVO> metricsVOS = metricsService.selectLatest(dateTime.toString(), dateTime.plusSeconds(30).toString());
                //有4个指标
                if (metricsVOS.size()==4){
                    Exceed exceed = new Exceed();
                    //通过指标对exceed赋值
                    for (MetricsVO metricsVo : metricsVOS) {
                        if (metricsVo.getMetricName().equals("node_memory_MemTotal_bytes")){
                            exceed.setNodeMemoryMemTotalBytes(metricsVo.getValue());
                        }
                        if (metricsVo.getMetricName().equals("node_memory_MemFree_bytes")){
                            exceed.setNodeMemoryMemFreeBytes(metricsVo.getValue());
                        }
                        if (metricsVo.getMetricName().equals("node_memory_Buffers_bytes")){
                            exceed.setNodeMemoryBuffersBytes(metricsVo.getValue());
                        }
                        if (metricsVo.getMetricName().equals("node_memory_Cached_bytes")){
                            exceed.setNodeMemoryCachedBytes(metricsVo.getValue());
                        }
                    }
                    //对Exceed判断
                    Boolean flag = TheNumberIsExceed(exceed,rule.getValue());
                    if (flag){
                        log.info("主机内存使用率超过80%");
                        //metricsId不同，需要多次传
                        for (MetricsVO metricsVO : metricsVOS) {
                            alertsService.add(new Alerts(metricsVO.getMetricId(),rule.getRuleName()));
                        }
                    }
                }
            }
            //判断主机网卡入口流量过高
            if (rule.getMetricName().equals("many2")){
                //前后60秒
                RateVO rateVO = metricsService.selectRate(dateTime.minusSeconds(30).toString(), dateTime.plusSeconds(30).toString());
                if (Objects.nonNull(rateVO)){
                    Boolean tooHigh = isTooHigh(rateVO,rule.getValue());
                    if (tooHigh){
                        log.info("主机网卡入口流量过高");
                        alertsService.add(new Alerts(rateVO.getMetricId(),rule.getRuleName()));
                    }
                }else {
                    log.info("没有新数据了");
                }
            }
        }
        dateTime = dateTime.plusSeconds(30L);
        System.out.println("现在时间：" + dateTime.format(formatter));

    }
}
